import random
import json
# n means the number of simulation for a chosen K
# In this task I chose n = 100,000 which means that
# for the chosen K I run 100,000 times to get the 
# expectation of E
def simulation(K_end=20,p=0.8,n=100000):
    ans = dict()
    ans['K_end'] = K_end
    ans['p'] = p
    ans['n'] = n
    with open('log.txt','w') as f:
        f.write(f'K_end = {K_end} , p = {p} , n = {n}\n')
        for K in range(0,K_end+1):
            E = 0
            for index in range(n):
                x1 = 0
                x2 = 0
                # while x1 < (x2 + K + 2) and (x1 + x2) < 100:
                while x1 < (x2 + K + 2):
                    if random.random() < p:
                        x1 += 1
                    else:
                        x2 += 1
                E += (100 - x1 - x2) / n
            print(f'K = {K}')
            ans[K] = E
            f.write(f'K = {K}, E = {E}\n')
        json_content = json.dumps(ans)
        with open('log.json','w') as f1:
            f1.write(json_content)


if __name__ == '__main__':
    simulation()